package com.javatian.service.impl;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javatian.dao.MessageInfoDao;
import com.javatian.entity.Account;
import com.javatian.entity.MessageInfo;
import com.javatian.service.MessageInfoService;
import com.javatian.vo.MessageInfoVo;
import exception.CustomException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 留言信息对外提供的服务实现类
 */
@Service("messageInfoService")
public class MessageInfoServiceImpl implements MessageInfoService {
    @Resource
    private MessageInfoDao messageInfoDao;


    /**
     * 增加一条记录
     */
    @Override
    public MessageInfo add(MessageInfo messageInfo,Account account) {
        if (account == null){
            throw new CustomException("1001","请先登录！");
        }
        messageInfo.setCreateTime(DateUtil.formatDateTime(new Date()));
        String content = messageInfo.getContent();
        if (content.length()>255){
            messageInfo.setContent(content.substring(0,250));
        }
        messageInfo.setName(account.getName());
        messageInfoDao.insertSelective(messageInfo);
        return messageInfo;
    }

    /**
     * 删除一条记录
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        messageInfoDao.deleteByPrimaryKey(id);

    }

    /**
     * 修改一条记录
     *
     * @param messageInfo
     */
    @Override
    public void update(MessageInfo messageInfo) {
        String content = messageInfo.getContent();
        if (content.length()>255){
            messageInfo.setContent(content.substring(0,250));
        }
        messageInfoDao.updateByPrimaryKeySelective(messageInfo);

    }

    /**
     * 根据主键查询一条记录
     *
     * @param id
     */
    @Override
    public MessageInfo findById(Long id) {
        return messageInfoDao.selectByPrimaryKey(id);
    }

    /**
     * 查询所有留言信息
     */
    @Override
    public List<MessageInfoVo> findAll() {
        List<MessageInfoVo> all = messageInfoDao.findByParentId(0L);
        for (MessageInfoVo messageInfoVo:all){
            List<MessageInfoVo> children = messageInfoDao.findByParentId(messageInfoVo.getId());
            messageInfoVo.setChildren(children);
        }
        return all;

    }


    /**
     * 根据条件分页查询
     * @param name
     * @param pageNum  第几页
     * @param pageSize 每页数量
     * @return 当前页的List列表
     */
    @Override
    public PageInfo<MessageInfoVo> findPage(String name,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<MessageInfoVo> all = messageInfoDao.findByName(name);
        return PageInfo.of(all);
    }

    /**
     * 根据内容模糊查询留言列表
     */
    @Override
    public List<MessageInfoVo> findByName(String name) {
        return messageInfoDao.findByName(name);
    }


}
